package org.yufan.admin.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.yufan.admin.result.PicUploadResult;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.UUID;

/**
 * Created by zxd on 2019/3/5
 **/
@Controller
@RequestMapping("/pic")
public class UploadController {

    private Logger LOGGER=LoggerFactory.getLogger(UploadController.class);

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public PicUploadResult upload(@RequestParam  MultipartFile uploadFile){
        PicUploadResult picUploadResult=new PicUploadResult();
        try{

            String path="F:\\image";
            String url="http://image.yufan.com//";


            //生成图片名字
            String filename=uploadFile.getOriginalFilename();
            LOGGER.debug("上传图片文件名为:{}",filename);
            String newName=UUID.randomUUID().toString().replace("-","")
                    +filename.substring(filename.lastIndexOf("."));

            LOGGER.debug("生成的文件名为:{}",newName);

            File directory=new File(path);
            if(!directory.exists()){
                directory.mkdirs();
                LOGGER.debug("创建文件夹:{}",directory.getPath());
            }
            File file=new File(path+File.separator+newName);
            //存储图片
            uploadFile.transferTo(file);
            LOGGER.debug("存储到服务器路径{}",file.getPath());

            BufferedImage bufferedImage=ImageIO.read(file);
            if(bufferedImage!=null){
                //上传成功
                picUploadResult.setError(0);
                picUploadResult.setUrl(url+newName);
                picUploadResult.setWidth(bufferedImage.getWidth()+"");
                picUploadResult.setHeight(bufferedImage.getHeight()+"");
                LOGGER.debug("上传图片成功,url:{}",url+newName);
            }else {
                picUploadResult.setError(1);
                picUploadResult.setMessage("图片上传失败!");
                LOGGER.error("上传图片失败!");
            }
        }catch (Exception e){
            LOGGER.error("上传图片失败,error:{}",e.getMessage());
            picUploadResult.setError(1);
            picUploadResult.setMessage("图片上传失败!");
        }
       return picUploadResult;
    }


}
